<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>菜单列表</title>
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<link rel="stylesheet" href="../../css/oksub.css">
	<script type="text/javascript" src="../../lib/loading/okLoading.js"></script>
</head>
<body>
<div class="ok-body">
	<!--模糊搜索区域-->
	<!--<div class="layui-row">-->
		<!--<form class="layui-form layui-col-md12 ok-search">-->
			<!--<input class="layui-input" placeholder="开始日期" autocomplete="off" id="startTime" name="startTime">-->
			<!--<input class="layui-input" placeholder="截止日期" autocomplete="off" id="endTime" name="endTime">-->
			<!--<input class="layui-input" placeholder="请输入角色名" autocomplete="off" name="name">-->
			<!--<button class="layui-btn" lay-submit="" lay-filter="search">-->
				<!--<i class="layui-icon layui-icon-search"></i>-->
			<!--</button>-->
		<!--</form>-->
	<!--</div>-->
	<!--数据表格-->
	<table class="layui-hide" id="tableId" lay-filter="tableFilter"></table>
</div>
<!--js逻辑-->
<script src="../../lib/layui/layui.js"></script>
<script src="../../libme/pages/body.js"></script>
<script>
	layui.use(["element", "table", "treetable", "okMock", "jquery","util","api"], function () {
		let table = layui.table;
		let okUtils = layui.okUtils;
		let treetable = layui.treetable;
		let okMock = layui.okMock;
		let util = layui.util;
		let $ = layui.jquery;
		let api = layui.api;
		okLoading.close();
		// laydate.render({elem: "#startTime", type: "datetime"});
		// laydate.render({elem: "#endTime", type: "datetime"});

		let menuTable = table.render({
			elem: "#tableId",
			url: okMock.api.menu.list,
			limit: 10,
			page: true,
			toolbar: "#toolbarTpl",
			//size: "lg",
            //height: 'full-20',
            beforeSuccessDone: function (res, curr) {
                if(res.code !== api.responseCode.success) {
                    api.defaultErrorhandler(res)
                    return false;
                }
            },
            parseData: function (res) {
                return {
                    code: res.code,
                    msg: res.name,
                    //count: res.code == RESP_SUCCESS ? res.extend.page.totalCounts : 0,
                    count: res.extend.page.totalCounts,
                    //data: res.code == RESP_SUCCESS ? res.extend.page.data.list : ''
                    data: res.extend.page.data.list
                };
            },
            request: {
                pageName:'currentPage',
                limitName:'pageCounts'
            },
            response: {
                statusCode: "100"
            },
			cols: [[
				{type: "checkbox", width: 50, fixed: "left"},
				{type: "numbers", title:'序号' , width: 50, fixed: "left"},
                {field: "title", title: "菜单名称", width: 130,align: "center", fixed: "left"},
				{field: "type", title: "菜单类型", width: 100,align: "center", templet: "#typeTpl", fixed: "left"},
                {field: "permissionCode", title: "权限标识", width: 130},
				{field: "menuCode", title: "菜单标识", width: 100},
				{field: "menuId", title: "菜单ID", width: 100, sort: true},
				{field: "parentId", title: "上级菜单ID", width: 100},
				{field: "sortno", title: "排序编号", width: 100,align: "center"},
                {field: "fontFamily", title: "图标类型", width: 100,align: "center"},
                {field: "icon", title: "图标样式", width: 100,align: "center"},
                {field: "href", title: "菜单链接", width: 200},
                {field: "target", title: "打开方式", width: 100,align: "center"},
                {field: "createBy", title: "创建人员", width: 120,align: "center",
                    templet: function (d) {
                        if(d.createBy == null || d.createBy == '') {
                            return '-'
                        }
                        return d.createBy
                    }
                },
                {field: "createAt", title: "创建时间", width: 120,align: "center",
                    templet: function(d){
                        const d_createAt = d.createAt
                        if(d_createAt == null){
                            return '-'
                        }
                        return util.toDateString(d_createAt, 'yyyy-MM-dd')
                    }
                },
                {field: "updateBy", title: "修改人员", width: 120,align: "center",
                    templet: function (d) {
                        if(d.updateBy == null || d.updateBy == '') {
                            return '-'
                        }
                        return d.updateBy
                    }
                },
                {field: "updateAt", title: "修改时间", width: 120,align: "center",
                    templet: function(d){
                        const d_updateAt = d.updateAt
                        if(d_updateAt == null){
                            return '-'
                        }
                        return util.toDateString(d_updateAt, 'yyyy-MM-dd')
                    }
                },
				{field: "remark", title: "备注", width: 200},
				{title: "操作", align: "center", fixed: "right", width: 120, templet: "#operationTpl"}
			]],
			done: function (res, curr, count) {// 服务器返回数据, 当前页码, 总记录数
				//console.log(res, curr, count);
                api.doShowUserPermsMenus()
			}
		});

		// form.on("submit(search)", function (data) {
         //    userTable.reload({
		// 		where: data.field,
		// 		page: {curr: 1}
		// 	});
		// 	console.log("0000")
		// 	return false;
		// });

		table.on("toolbar(tableFilter)", function (obj) {
			switch (obj.event) {
				case "create":
					add();
					break;
				case "batchDel":
					batchDel();
					break;
			}
		});

		table.on("tool(tableFilter)", function (obj) {
			let data = obj.data;
			switch (obj.event) {
				case "modify":
					edit(data.id, data);
					break;
				case "delete":
					del(data);
					break;
				case "perms":
				    perms(data);
				    break;
			}
		});

		function add() {
			okLayer.open("添加菜单", "menu-add.html", "90%", "90%", null, function () {
                menuTable.reload();
			})
		}

		function batchDel() {
			okLayer.confirm("确定要批量删除吗？", function (index) {
				layer.close(index);
                var checkStatusData = table.checkStatus('tableId').data;
				var ids = [];
				if(checkStatusData.length > 0 ) {
                    $.each(checkStatusData, function (idx, obj) {
                        ids.push(obj.menuId)
                    })
                }else{
                    layer.msg("未选择有效数据", {offset: "t", anim: 6});
                    return;
				}
				//console.log(ids)
				if (ids.length > 0) {
					deleteByIds(ids)
				}
			});
		}

		function edit(id, data) {
			okLayer.open("编辑角色", "menu-edit.html?id=" + id, "90%", "90%",
				function (layero, index) {//successFunction
                    //var paraString = location.search;//URL传递的?后部分
                    //console.log(paraString)
					//console.log('url=' + layui.url());
                    //var router = layui.router();
                    //console.log(router.search.id)//获取不到search
					//console.log(data)

					//回显数据
                    var body = layer.getChildFrame('body', index);//获取弹出层的dom元素
					body.find("input[name='menuId']").val(data.menuId)
					body.find("input[name='title']").val(data.title)

					// 类型 radio 赋值
					var eleType = body.find("input[name='type'][value='"+ data.type +"']")
					$(eleType).attr('checked', true)

                    //回显子窗口的表单显示隐藏
                    const menuType = data.type
                    if(menuType == 'M'){//目录
                        body.find('input[name="menuCode"]').parents('.layui-form-item').css('display', 'none');
                        body.find('input[name="href"]').prop('disabled', true);
                    }else if(menuType == 'C'){//菜单
                        body.find('input[name="menuCode"]').parents('.layui-form-item').css('display', 'none');
                        body.find('input[name="href"]').prop('disabled', false);
                    }else if(menuType == 'F'){//按钮
                        body.find('input[name="menuCode"]').parents('.layui-form-item').css('display', 'block');
                        body.find('input[name="href"]').prop('disabled', true);
                    }

					body.find("input[name='menuCode']").val(data.menuCode)
					body.find("input[name='href']").val(data.href)

					// 图标类型
					$(body.find("input[name='fontFamily'][value='"+ data.fontFamily +"']")).attr('checked', true)
					// 图标样式
					$(body.find("input[name='icon'][value='"+ data.icon +"']")).attr('checked', true)

					//body.find("input[name='fontFamily']").val(data.fontFamily)
					// 上级菜单
					//var parentOpt = $(body.find("select[name='parentId']")).html()

					//回显下拉框数据 菜单
                    var eleParent = body.find("#parentId")
					const list = JSON.parse(sessionStorage.getItem("menu-select-box"))
					//console.log(list)
                    eleParent.append('<option value="0">顶级目录</option>')
					doShowMenuSelectBox(list, "", data.parentId, eleParent)
					//form.render('select','permission')

					body.find("input[name='sortno']").val(data.sortno)
					body.find("input[name='remark']").val(data.remark)
            	},
				function () {//endFunction
                	menuTable.reload();
					//console.log("end function")
				}
			)
		}

		function del(data) {
			okLayer.confirm("确定要删除吗？", function () {
			    var ids = []
				ids.push(data.menuId)
                deleteByIds(ids)
			})
		}

		function perms(data) {
            okLayer.open("修改权限", "menu-perms.html", "90%", "90%",
				function (layero, index) {
                	//menuTable.reload();

                    //回显数据
                    var body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                    body.find("input[name='menuId']").val(data.menuId)

                    body.find("input[name='title']").val(data.title)

                    // 类型 radio 赋值
                    var eleType = body.find("input[name='type'][value='"+ data.type +"']")
                    $(eleType).attr('checked', true)

                    // 权限
                    var elePermission = body.find("#permissionId")
                    $(elePermission).append('<option value="">--- 请选择权限 ---</option>')
                    $.each(JSON.parse(sessionStorage.getItem("permission-select-box")),function(index, obj){
                        //console.log(obj.permissionId)
                        $(elePermission).append('<option value="'+ obj.permissionId +'" disabled>'+ obj.permissionName +'</option>')
                        var childs = obj.children
                        if(childs != null && childs.length > 0){
                            $.each(childs, function (i, c) {
                                if(c.permissionId == data.permissionId) {
                                    //console.log('>'+ c.permissionId + "/" + data.permissionId)
                                    $(elePermission).append('<option value="'+ c.permissionId +'" selected>'+ '&nbsp;&nbsp;&nbsp;&nbsp;|----&nbsp;' +  c.permissionName +'</option>')
                                }else{
                                    //console.log('<'+ c.permissionId + "/" + data.permissionId)
                                    $(elePermission).append('<option value="'+ c.permissionId +'">'+ '&nbsp;&nbsp;&nbsp;&nbsp;|----&nbsp;' +  c.permissionName +'</option>')
                                }

                            })
                        }
                    });

            	},
                function () {//endFunction
                    menuTable.reload();
                    //console.log("end function")
                }
            )
        }

        function doShowMenuSelectBox(list, prefix, parentid, eleObj) {
            $.each(list, function (index, obj) {
                if(obj.menuId == parentid) {
                    eleObj.append('<option value="'+ obj.menuId +'" selected>' + prefix + obj.title +'</option>')
                }else{
                    eleObj.append('<option value="'+ obj.menuId +'">' + prefix + obj.title +'</option>')
				}
                var childs = obj.children
                if(childs.length > 0){
                    doShowMenuSelectBox(childs, '&nbsp;&nbsp;&nbsp;&nbsp;|----&nbsp;', parentid ,eleObj)
                }
            })
        }

		function deleteByIds(ids) {
			api.request({
				url: okMock.api.menu.deleteByIds,
				where:{ids: ids},
                traditional: true
			},function (resp, stat) {
                okUtils.tableSuccessMsg(resp.name);
            },function () {
                menuTable.reload();
            })
        }


	})
</script>
<!-- 头工具栏模板 -->
<script type="text/html" id="toolbarTpl">
	<div class="layui-btn-container">
		<div class="layui-inline menu-create layui-hide" lay-event="create"><i class="layui-icon layui-icon-add-1"></i></div>
		<div class="layui-inline menu-delete layui-hide" lay-event="batchDel"><i class="layui-icon layui-icon-delete"></i></div>
	</div>
</script>
<!-- 行工具栏模板 -->
<script type="text/html" id="typeTpl">
	{{#  if(d.type == 'M'){ }}
	<span class="layui-badge layui-bg-orange">目录</span>
	{{#  } else if(d.type == 'C') { }}
	<span class="layui-badge layui-bg-blue">菜单</span>
	{{#  } else if(d.type == 'F') { }}
	<span class="layui-badge layui-bg-black">按钮</span>
	{{#  } }}
</script>

<script type="text/html" id="operationTpl">
	<a href="javascript:" title="编辑" class="menu-modify layui-hide" lay-event="modify"><i class="layui-icon">&#xe642;</i></a>
	<a href="javascript:" title="删除" class="menu-delete layui-hide" lay-event="delete"><i class="layui-icon">&#xe640;</i></a>
	<a href="javascript:" title="授权" class="menu-perms layui-hide" lay-event="perms"><i class="layui-icon">&#xe612;</i></a>
</script>
</body>
</html>
